/**********************************************************************
 Name:  AuditPlanControl
 Purpose:search out all audit plan and show them                               
======================================================
History                                                            
-------                                                            
VERSION  AUTHOR            DATE              DETAIL                                
   1.0         li siheng         2011-3-15        Create      
======================================================
Review History                                                            
-------  
VERSION    REVIEWER     DATE          DETAIL
  1.0         WP      05/06/2011    1. 页面布局和代码缩进混乱
                                    2. 变量、属性、方法均缺少注释
                                    3. 几个方法体中使用了多个7、6等常量，应该在全局做常量定义，方便控制
                                    4. userId全局变量只在GetData中使用，为何要命名成全局变量？应该是局部变量
                                    5. GetData使用了startDate2、endDate2全局变量，此处的代码不是最佳做法，应该给GetData方法定义参数，通过参数传递需要的值。
                                    6. 问题4和5中透露出的问题是何时使用全局变量，何时使用局部变量，何时使用参数传递，开发人员没有进行过清晰的思考，需要注意。
                                    7. News方法命名很奇怪，方法命名应包含一个动作，而不是一个名词
                                    8. testMethod需要考虑到所有使用此功能的角色  
***********************************************************************/
public class AuditPlanControl{


        public Date weekStart{get;set;}
        public List<audit_plan__c> apList{get;set;}
        public Date startDate2{get;set;}
        public Date endDate2{get;set;}
        public String yearId{get;set;}
        public String monthId{get;set;}
        public string userid{get;set;}
        public String test{get;set;}
    
    public List<SelectOption> listOption{
        get
        {
            if(listOption==null)
                    listOption=new List<SelectOption>();
            else
                    listOption.clear();
                    
            Integer y=Date.Today().year();
           
            for(Integer i=2010;i<=y+1;i++)
            {
                if(i!=y)
                   listOption.add(new SelectOption(String.valueof(i),String.valueof(i)));
                else
                   listOption.add(new SelectOption(String.valueof(i),String.valueof(i),false));

            }
           
            return listOption;
        }
        set;}
        
    public List<SelectOption> listOptionMonth{
        get
        {
            if(listOptionMonth==null)
                    listOptionMonth=new List<SelectOption>();
            else
                    listOptionMonth.clear();
                    
             Integer Month=System.Today().month();
             
             for(Integer i=1;i<=12;i++)
             {
                if(i!=Month)
                    listOptionMonth.add(new SelectOption(String.valueOf(i),String.valueOf(i)));
                else
                   listOptionMonth.add(new SelectOption(String.valueOf(i),String.valueOf(i),false));

             }
             
            return listOptionMonth;
        }set;
    }
    
    //递归找出下级的所有TSR
    public void GetTsrId(Id id)
    {
      for(User u:[select Id,Name,Title__c,FunctionDepartment__c from User where ManagerId=:Id])
      {
        if(u.Title__c == 'Sales Rep' && ((u.FunctionDepartment__c=='Trade Sales')||(u.FunctionDepartment__c=='Trade&Medical Sales')))
        {
            
        }
        else
        {
            if((u.FunctionDepartment__c=='Trade Sales')||(u.FunctionDepartment__c=='Trade&Medical Sales'))
                listOptionTSR.add(new SelectOption(u.Id,u.Name));
            GetTsrId(u.Id);
        }
      }
    }    
    
    public List<SelectOption> listOptionTSR
    {
        get;
        set;
    }

        
    //切换到下一周
    public PageReference Next()
    {
       startDate2  = startDate2.addDays(7);
       endDate2 = endDate2.addDays(7);
   
       apList=GetData();
   
        return null;
    }
    //切换到上一周
    public PageReference Previous()
    {
        startDate2  = startDate2.addDays(-7);//-7
        endDate2 = endDate2.addDays(-7);//-7
    
        apList=GetData();
   
        return null;
    }
    public PageReference Searchs()
    {
        Integer year;
        Integer month;
        if(yearId==NULL)
            year=Date.Today().year();
        else
            year=Integer.valueof(yearId);
        
        if(monthId==NULL)
            month=Date.Today().month();
        else
            month=Integer.valueof(monthId);
                        
        Date d=Date.newInstance(year,month,1);
        startDate2  = d.toStartOfWeek();
        endDate2 = startDate2.addDays(6);

        apList=GetData();
        return null;
    }
        
    public List<Audit_Plan__c> GetData()
    {
        if(userId ==NULL || userId =='0')
                userId =UserInfo.getUserId();
        
        return [Select r.Name, r.Id,r.audit_Date__C,r.OwnerId,(Select  id,Name,Sort__c,Outlet__c,in_store_visit__c,outletID__c,TSR__c, OutletCode__c From audit__r order by Sort__c asc) 
            From audit_plan__c r where  audit_Date__c >= :startDate2 and audit_Date__c<= :endDate2 and OwnerId=:userId order by audit_Date__c asc ];
        
    }
        
    public PageReference News()
    {
        // String Prefix = Audit__c.sObjectType.getDescribe().getKeyPrefix();   
         String tempURL = '/apex/createauditpage?retURL=/apex/auditplanpage';
         PageReference TempRef = new PageReference(tempURL);
         TempRef.setRedirect(true);
         return TempRef;
    }

    
    public AuditPlanControl() {

        if(listOptionTSR==null)
            listOptionTSR=new List<SelectOption>();
        else
            listOptionTSR.clear();
                
        listOptionTSR.add(new SelectOption('0','Current User'));
        Profile p=[select Name from Profile where Id=: UserInfo.getProfileId()];
        test=p.Name;
        
        //如果是系统管理员加载所有的TSR否则加载所有的
        if(p.Name=='System Administrator' || p.Name=='系统管理员')
        {
            for(User u:[select Id,Name from User where Title__c !='Sales Rep' and FunctionDepartment__c='Trade Sales'])//添加所有TSR
            {
                listOptionTSR.add(new SelectOption(u.Id,u.Name));
            }
        }
        else
        {
           User u=[select Id,Name,Title__c,UserRegion__c,FunctionDepartment__c from User where Id=:UserInfo.getUserId()];
           if(u.Title__c=='Regional General Manager')
           {
                for(User ur:[select Id,Name from User where (FunctionDepartment__c='Trade Sales' or FunctionDepartment__c='Trade&Medical Sales') and  Title__c !='Sales Rep' and Title__c != 'Regional General Manager' and UserRegion__c =: u.UserRegion__c])//添加所有属下
                {
                    listOptionTSR.add(new SelectOption(ur.Id,ur.Name));
                }                  
           }
           else
           {
               GetTsrId(u.Id);
           }

        }

        yearId=String.valueOf(System.Today().Year());
        monthId=String.valueOf(System.Today().Month());
        
        startDate2 =  Date.today().toStartOfWeek();
        endDate2 = startDate2.addDays(6);
    
        apList=GetData();        

    }
    
    static testMethod  void test()
    {
        Profile p = [select id from profile where name='System Administrator' or name = '系统管理员' limit 1];
        User u2 = new User(alias = 'standtss', email='sdardr@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',Title__c='TSR',
        localesidkey='en_US', profileid = p.Id,UserCity__c='广州',IsActive=true,
        UserAreaValue__c='广州区域',UserSubRegion__c='华南一区',UserRegion__c='华南区',
        timezonesidkey='America/Los_Angeles', username='stsers@testorg.com');
        insert u2;  
        
        system.runas(u2){
                Audit_Plan__c auditplan=new Audit_Plan__c();
        }
        
     }
 }